package com.hw.weathershow.websocket;

import com.hw.weathershow.entity.Weather;
import com.hw.weathershow.factory.ProduceFactory;
import com.hw.weathershow.factory.ServiceFactory;
import com.hw.weathershow.factory.getter.MapperFactory;
import com.hw.weathershow.mapper.WeatherMapper;
import com.hw.weathershow.observer.WeatherObserver;
import com.hw.weathershow.util.ResponseJson;
import org.apache.logging.log4j.spi.LoggerRegistry;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * The type Update weather socket.
 *
 * @author Cejay1314
 * @version 1.0
 * @create 2022 /12/5 23:23
 */
@ServerEndpoint(value = "/websocket") //接受websocket请求路径
@Component
public class UpdateWeatherSocket {
    /**
     * The Weather mapper.
     */
    @Autowired
    WeatherMapper weatherMapper;
    //保存所有在线socket连接
    private static Map<String,UpdateWeatherSocket> webSocketMap = new LinkedHashMap<>();

    //记录当前在线数目
    private static int count=0;

    //当前连接（每个websocket连入都会创建一个UpdateWeatherSocket实例
    private Session session;

    /**
     * On open.
     *
     * @param session the session
     * @throws IOException     the io exception
     * @throws EncodeException the encode exception
     */
//处理连接建立
    @OnOpen
    public void onOpen(Session session) throws IOException, EncodeException {
        this.session=session;
        webSocketMap.put(session.getId(),this);
        addCount();
        System.out.println("新的连接加入：{" + session.getId() + "}，当前连接数为：" + UpdateWeatherSocket.getCount());
//
//
//        Weather weather = null;
//        List<Weather> weathers = weatherMapper.selectList(null);
//        if(weathers.size()>0){
//            weather = weathers.get(0);
//            String responseJson = new ResponseJson().success()
//                    .setData("city", weather.getCity())
//                    .setData("province", weather.getProvince())
//                    .setData("weather", weather.getWeather())
//                    .setData("temperature", weather.getTemperature())
//                    .setData("windDirection", weather.getWindDirection())
//                    .setData("windPower", weather.getWindPower())
//                    .setData("humidity", weather.getHumidity())
//                    .toString();
//            this.session.getBasicRemote().sendText(responseJson.toString());
//        }
    }

    /**
     * On message.
     *
     * @param message the message
     * @param session the session
     */
//接受消息
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("收到客户端{" + session.getId() + "}消息：{" + message + "}");
        try{
            this.sendMessage("收到消息："+message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * On error.
     *
     * @param error   the error
     * @param session the session
     */
//处理错误
    @OnError
    public void onError(Throwable error, Session session){
    }

    /**
     * On close.
     */
//处理连接关闭
    @OnClose
    public void onClose(){
        webSocketMap.remove(this.session.getId());
        reduceCount();
        System.out.println("有连接断开，当前连接数为：" + UpdateWeatherSocket.getCount());
    }

    //群发消息

    /**
     * Send message.
     *
     * @param message the message
     * @throws IOException the io exception
     */
//发送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * Send object.
     *
     * @param message the message
     * @throws IOException     the io exception
     * @throws EncodeException the encode exception
     */
//发送对象
    public void sendObject(Object message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }


    /**
     * Broadcast.
     */
//广播消息
    public void broadcast(){
        UpdateWeatherSocket.webSocketMap.forEach((k,v)->{
            try{
                v.sendMessage("这是一条测试广播");
            }catch (Exception e){
            }
        });
    }

    /**
     * Update weather.
     *
     * @param weather the weather
     */
//更新天气
    public void updateWeather(String weather){
        UpdateWeatherSocket.webSocketMap.forEach((k,v)->{
            try{
                v.sendMessage(weather);
            }catch (Exception e){
            }
        });
    }

    /**
     * Get count int.
     *
     * @return the int
     */
//获取在线连接数目
    public static int getCount(){
        return count;
    }

    /**
     * Add count.
     */
//操作count，使用synchronized确保线程安全
    public static synchronized void addCount(){
        UpdateWeatherSocket.count++;
    }

    /**
     * Reduce count.
     */
    public static synchronized void reduceCount(){
        UpdateWeatherSocket.count--;
    }
}
